package com.yilijk.base.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AppOpsManager;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.view.Window;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.yilijk.base.AppBase;
import com.yilijk.base.network.config.BaseConfig;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public
class CommonUtils {

    private Gson gson = new Gson();
    private static CommonUtils moduleCommonUtils = new CommonUtils();
    private ExecutorService executorService = Executors.newCachedThreadPool();
    private ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
    private ConnectivityManager connectivityManager;


    public static CommonUtils getModuleCommonUtils() {
        if (moduleCommonUtils == null) {
            moduleCommonUtils = new CommonUtils();
        }

        return moduleCommonUtils;
    }

    //线程池
    public ExecutorService getExecutorService() {
        return executorService;
    }


    public ExecutorService getSingleThreadExecutor() {
        return singleThreadExecutor;
    }

    //获取状态栏的宽高
    public int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    public static void loginfo(String logMessage) {
        ALog.d(logMessage);
    }


    public static JSONObject toJson(String str) {
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(str);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    public static String toString(JsonObject jsonObject) {
        String s = jsonObject.toString();
        return s;
    }

    public String GsontoString(HashMap<String, Object> hashMap) {
        return new Gson().toJson(hashMap);
    }


    public static String imageTranslateUri(Context context, int resId) {
        if (context!=null){
            Resources resources = context.getResources();
            Uri uri = Uri.parse(
                    ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                            + resources.getResourcePackageName(resId) + "/"
                            + resources.getResourceTypeName(resId) + "/"
                            + resources.getResourceEntryName(resId)
            );
            return uri.toString();
        }
        return "";




    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static String decodeUTF8(String content) {
        if (content.isEmpty()) {
            return "暂无消息";
        }
//判断是否是集合
// 解析
// 直接返回
        if (String.valueOf(content.charAt(0)).equals("[") && String.valueOf(content.charAt(content.length() - 1)).equals("]")) {
            Gson gson = new Gson();
            List<Integer> list = gson.fromJson(content, new TypeToken<List<Integer>>() {
            }.getType());
            if (list.size() == 0) {
                return null;
            }
            String encoded = "";
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i) != 10) {
                    //转码
                    String s = Integer.toHexString(list.get(i));
                    encoded += "%" + s;
                }
            }
            String decode = "";
            try {
                ALog.d("encoded", "convert: " + encoded);
                decode = URLDecoder.decode(encoded, "utf-8");
                ALog.d("decode", "convert: " + decode);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return decode;
        } else {
            return content;
        }
    }


    public String getMaptoJson(HashMap<String, Object> map) {
        String s = gson.toJson(map);
        return s;
    }

    //获取设备权限
    public void setRequestPermission(Activity activity, String[] strings, int requestCode) {
//        >=23
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            activity.requestPermissions(strings, requestCode);
        }
    }


    public String Uri2Path(Context context, String uriString) {
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(Uri.parse(uriString),
                filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        ALog.d("requestNet", "picturePath: " + picturePath);
        return picturePath;
    }

    public Uri getMediaUriFromPath(Context context, String path) {
        Uri mediaUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        Cursor cursor = context.getContentResolver().query(mediaUri,
                null,
                MediaStore.Images.Media.DISPLAY_NAME + "= ?",
                new String[]{path.substring(path.lastIndexOf("/") + 1)},
                null);

        Uri uri = null;
        if (cursor.moveToFirst()) {
            uri = ContentUris.withAppendedId(mediaUri,
                    cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
        }
        cursor.close();
        return uri;
    }


    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 获取通知权限
     *
     * @param context
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public boolean isNotificationEnabled(Context context) {

        String CHECK_OP_NO_THROW = "checkOpNoThrow";
        String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

        AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();
        int uid = appInfo.uid;

        Class appOpsClass = null;
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE,
                    String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);

            int value = (Integer) opPostNotificationValue.get(Integer.class);
            return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    public static JSONObject combineJson(JSONObject srcObj, JSONObject addObj) throws JSONException {
        Iterator<String> itKeys1 = addObj.keys();
        String key, value;
        while (itKeys1.hasNext()) {
            key = itKeys1.next();
            value = addObj.optString(key);
            srcObj.put(key, value);
        }
        return srcObj;
    }

    public static ArrayList list(ArrayList al) {
        ArrayList newal = new ArrayList();//新建一个中间集合
        for (Iterator it = al.iterator(); it.hasNext(); )//集合循环
        {
            Object obj = it.next();
            if (!newal.contains(obj))//不包含重复的输出
                newal.add(obj);
        }
        return newal;
    }

    //loading 动画
    public boolean isNetWorkAvailavle(Activity activity) {
        connectivityManager = (ConnectivityManager) AppBase.getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null) {
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }


    public static JSONObject String2JSON(String string) {
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(string);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }


    public static void Itoast_Exception(Context context) {
//        handler.post(new Runnable() {
//            @Override
//            public void run() {
//                Toast.makeText(context, "互联网医院请求出错", Toast.LENGTH_SHORT).show();
//            }
//        });
        try {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context, "互联网医院请求出错", Toast.LENGTH_SHORT).show();
                }
            });
        } catch (Throwable throwable) {

        }
    }

    public static void Itoast_OutTime(Context context) {
//        handler.post(new Runnable() {
//            @Override
//            public void run() {
//                Toast.makeText(context, "互联网医院请求超时", Toast.LENGTH_SHORT).show();
//            }
//        });
        try {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context, "互联网医院请求超时", Toast.LENGTH_SHORT).show();
                }
            });
        } catch (Throwable throwable) {

        }
    }

    public static void Itoast(Context context, String message) {
//        handler.post(new Runnable() {
//            @Override
//            public void run() {
//                Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
//            }
//        });
        try {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
                }
            });
        } catch (Throwable throwable) {

        }
    }

    public static boolean request_code(Context context, String code) {
        ALog.i("request_code", "request_code: " + code);
        if (code.endsWith("Exception")) {
            code = "Exception";
        }
        boolean flag = false;
        switch (code) {
            case "500":
                Itoast(context, "互联网医院服务出错");
                flag = true;
                break;
            case "400":
                Itoast(context, "互联网医院请求出错");
                flag = true;
                break;
            case "404":
                Itoast(context, "互联网医院请求无效");
                flag = true;
                break;
            case "Exception":
//                Itoast(context,"互联网医院请求异常");
                flag = true;
                break;
            case "502":
                Itoast(context, "互联网医院请求异常");
                break;
            case "401":
            case "406":
                Intent loginintent = new Intent(BaseConfig.Receiver.BroadcastReceiver);
                loginintent.putExtra(BaseConfig.Constants.IsLogin, true);         //向广播接收器传递数据
                context.sendBroadcast(loginintent);      //发送广播
                break;
        }
        return flag;
    }

    public static String array2JSONString(ArrayList<String> array) {
        String s = new Gson().toJson(array);
        return s;

    }

    public static String long2Time(long timelong) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String format = simpleDateFormat.format(timelong);
        return format;
    }

    public static boolean isBase64(String str) {
        if (str.startsWith("https")) {
            return false;
        } else {
            return true;
        }
    }

    public static boolean checkPermission(Context context, String permission) {
        return (PackageManager.PERMISSION_GRANTED == context.getPackageManager().checkPermission(permission, context.getPackageName()));
    }

    /**
     * pop蒙版
     */
    public static void setBackgroundAlpha(PopupWindow popupWindow, Activity activity, float v) {
        if (popupWindow != null && popupWindow.isShowing()) {
            Window window = activity.getWindow();
            WindowManager.LayoutParams lp = window.getAttributes();
            window.setFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND, WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            lp.alpha = v; //0.0-1.0
            window.setAttributes(lp);
        }
    }

    public static void setBackgroundAlpha(Activity activity, float v) {
        Window window = activity.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        window.setFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND, WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        lp.alpha = v; //0.0-1.0
        window.setAttributes(lp);
    }

}
